local ResSync = LibStub("LibResSync-1.0", true)
if not ResSync then
	InvenRaidFrames3Member_UpdateResurrection = function() end
	InvenRaidFrames3Member_OnUpdateResurrectionBar = InvenRaidFrames3Member_UpdateResurrection
	return
end

local _G = _G
local IRF3 = _G[...]
local pairs = _G.pairs
local wipe = _G.table.wipe
local GetTime = _G.GetTime
local UnitInRaid = _G.UnitInRaid
local UnitInParty = _G.UnitInParty
local UnitCastingInfo = _G.UnitCastingInfo
local function UnitInGroup(unit)
	return UnitInRaid(unit) or UnitInParty(unit)
end
local resUnits, casters, castName, castStart, castEnd, _ = {}, {}
local delimiter = ","

ResSync.resurrectionSpells[GetSpellInfo(61999) or ""] = true
ResSync.resurrectionSpells[""] = nil

function InvenRaidFrames3Member_OnUpdateResurrectionBar(self)
	casters[1], casters[2], casters[3], casters[4], casters[5] = delimiter:split(self.caster)
	self.startTime, self.endTime = nil
	for _, caster in pairs(casters) do
		castName, _, _, _, castStart, castEnd = UnitCastingInfo(caster)
		if ResSync.resurrectionSpells[castName] then
			if not self.endTime or self.endTime < castEnd then
				self.startTime, self.endTime = castStart, castEnd
			end
		end
	end
	if self.startTime then
		self:SetMinMaxValues(self.startTime, self.endTime)
		self:SetValue(GetTime() * 1000)
	else
		self.caster = nil
		self:Hide()
	end
end

function InvenRaidFrames3Member_UpdateResurrection(self)
	if self.isGhost or self.isDead then
		self.resurrectionBar.caster = resUnits[ResSync:GetUnitName(self.displayedUnit)]
		if self.resurrectionBar.caster then
			if not self.resurrectionBar.ticker then
				self.resurrectionBar.ticker = C_Timer.NewTicker(0.02, function() InvenRaidFrames3Member_OnUpdateResurrectionBar(self.resurrectionBar) end)
			end
			self.resurrectionBar:Show()
		else
			if self.resurrectionBar.ticker then
				self.resurrectionBar.ticker:Cancel()
				self.resurrectionBar.ticker = nil
			end
			self.resurrectionBar:Hide()
		end
	else
		if self.resurrectionBar.ticker then
			self.resurrectionBar.ticker:Cancel()
			self.resurrectionBar.ticker = nil
		end
		self.resurrectionBar.caster = nil
		self.resurrectionBar:Hide()
	end
end

local eventHandler = CreateFrame("Frame")
eventHandler:SetScript("OnEvent", function(self, event, unit, spell)
	if ResSync.resurrectionSpells[spell] then
		wipe(resUnits)
		for caster, target in pairs(ResSync.castingTarget) do
			if UnitInGroup(caster) and UnitInGroup(target) then
				if resUnits[target] then
					resUnits[target] = resUnits[target]..","..caster
				else
					resUnits[target] = caster
				end
			end
		end
		for member in pairs(IRF3.visibleMembers) do
			if member.resurrectionBar then
				InvenRaidFrames3Member_UpdateResurrection(member)
			end
		end
	end
end)
eventHandler:RegisterEvent("UNIT_SPELLCAST_START")
eventHandler:RegisterEvent("UNIT_SPELLCAST_STOP")
